package net.keebook.webapp.ws;

import javax.ejb.Stateless;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import net.keebook.webapp.entity.KeeBook;
import net.keebook.webapp.entity.User;
import net.keebook.webapp.util.AccessRight;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;


@Path("/{username}/createkeebook")
@Stateless
public class CreateKeeBookService extends WebService {
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public String saveSettings(@PathParam("username") String username, String jsonString) {
		Logger.getLogger(this.getClass()).info("Incoming request");
		Logger.getLogger(this.getClass()).trace("Request string: " + jsonString);
		
		JSONObject input = getInput(jsonString);
		JSONObject result = new JSONObject();
		try {
			String password = input.getString("password");
			
			// Authentication
			User user = authenticate(username, password);
			if (user == null) {
				Logger.getLogger(this.getClass()).warn("Authentication failed for user " + username);
				result.put("authSuccess", false);
				result.put("success", false);
				return getResponse(result);
			}
			
			Logger.getLogger(this.getClass()).info("User " + username + " authenticated successfully (user id: "+user.getExposableId()+")");
			result.put("authSuccess", true);
			
			if (!input.has("data")) {
				Logger.getLogger(this.getClass()).warn("Data element missing in request");
				result.put("success", false);
				return getResponse(result);
			}
			
			JSONObject data = input.getJSONObject("data");
			if (!data.has("title") || !data.has("salt") || !data.has("keeBookChecksum")) {
				Logger.getLogger(this.getClass()).warn("One of the following elements have not been defined: title, salt, keeBookChecksum");
				result.put("success", false);
				return getResponse(result);
			}
			
			KeeBook keeBook = new KeeBook();
			keeBook.setName(data.getString("title"));
			keeBook.setSalt(data.getString("salt"));
			keeBook.setKeyphraseChecksum(data.getString("keeBookChecksum"));
			
			getKeeBookDao().store(keeBook);
			getKeeBookDao().setAccessRight(user, keeBook, AccessRight.OWNER);
			
			result.put("success", true);
			result.put("keeBookId", keeBook.getExposableId());
		} catch (JSONException e) {
			Logger.getLogger(this.getClass()).error("JSONException while request processing", e);
			return getResponse(ERROR_RESPONSE);
		}
		
		return getResponse(result);
	}
}
